from rest_framework import serializers


# 个人信息表序列化器
from rest_framework.serializers import ModelSerializer

from xj_users.models import User, Article


class UserInfoSerializer(serializers.Serializer):

    token = serializers.CharField(read_only=True)
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'avatar', 'token')
        # fields = '__all__'

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


#修改
class UsersInfoSerializer(serializers.Serializer):


    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    id = serializers.IntegerField(label='ID')
    realname = serializers.CharField(label='姓名')
    sex = serializers.IntegerField(label='性别')
    pub_date = serializers.DateField(label='出生日期')
    # 个人网站，手机号，email，现居，通讯地址
    website = serializers.CharField(label='个人网站')
    mobile = serializers.IntegerField(label='手机号')
    email = serializers.CharField(label='Email')
    city = serializers.CharField(label='现居')
    address = serializers.CharField(label='地址')
    avater = serializers.CharField(label='头像')


    #修改个人信息
    def update(self, instance, validated_data):

        instance.name = validated_data.get('name', instance.name)
        instance.sex = validated_data.get('sex', instance.sex)
        instance.pub_date = validated_data.get('pub_date', instance.pub_date)
        instance.website = validated_data.get('website', instance.website)
        instance.mobile = validated_data.get('mobile', instance.mobile)
        instance.email = validated_data.get('email', instance.email)
        instance.city = validated_data.get('city', instance.city)
        instance.address = validated_data.get('address', instance.address)
        instance.avatar = validated_data.get('avatar', instance.avatar)
        instance.save()

        return instance


# 用户序列化器
class UserSerializerSimple(ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'avatar')


# 关注用户序列化器
class AttentionUserSerializer(ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'label_name')


